#{extends 'main.html' /}
#{set title:'Map Statistics' /}
<style type="text/css">
    html {
        height: 100%
    }
    
    body {
        height: 100%;
        margin: 0px;
        padding: 0px
    }
    
    #map_canvas {
        height: 100%
    }
	
	.error {
    background: #c00 !important;
	}

	.success {
    background: #008800 !important;
	}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
	var markers = new Array();
	var map;
	var lastUpd;
	var dirServ = new google.maps.DirectionsService();
	var polyLines = new Array();
	var trigger_draw = 0;
	var rect = new google.maps.Rectangle();
	var popz = new google.maps.InfoWindow();
	
	function clearMarkers()
	{
		for (i in markers)
		{
			markers[i].setMap(null);
		}
		markers.splice(0,markers.length);		
	}
	
	function poll_updates()
	{
		if (!rect.getMap()) {
			$.ajax({
				url: "@{pollUpdates()}",
				async: false,
				success: function(data){
					$.each(data, function(key, val){
						//alert(val.device_id);
						lastUpd = val;
						create_marker(val);
					});
					var currDate = new Date().getTime();
					var timeDi = (currDate - lastUpd.date) / 60000;
					
					$('#info').html('<div class="success"></div>Showing data based on ' +
					data.length +
					' updates from the past ' +
					timeDi +
					' minutes');
					
				//alert(currDate-lastUpd.date);
				}
			});
		//alert(updates.length);
		}
		else
		{
			var velocity=0;
			$.ajax({
				url: "@{pollUpdatesByArea()}",
				data: {
					lon1: Math.min(rect.getBounds().getNorthEast().lng(), rect.getBounds().getSouthWest().lng()),
					lat1: Math.min(rect.getBounds().getNorthEast().lat(), rect.getBounds().getSouthWest().lat()),
					lon2: Math.max(rect.getBounds().getNorthEast().lng(), rect.getBounds().getSouthWest().lng()),
					lat2: Math.max(rect.getBounds().getNorthEast().lat(), rect.getBounds().getSouthWest().lat())
				},
				async: false,
				success: function(data){
					$.each(data, function(key, val){
						//alert(val.device_id);
						lastUpd = val;
						create_marker(val);
						velocity += val.speed;
					});
					var currDate = new Date().getTime();
					var timeDi = (currDate - lastUpd.date) / 60000;
					
					$('#info').html('<div class="success"></div>');
					popz.setContent('Avg. Velocity: '+velocity/data.length+'<br>#Updates: '+data.length+'<br>Since '+timeDi+' mins.');
				//alert(currDate-lastUpd.date);
				}
			});
		}
	}
	
	function create_marker(data)
	{
		var approximated = approx_to_nearest_road(data.latitude, data.longitude);
		if (approximated.length == 0) {
			marker = new google.maps.Marker({
				position: new google.maps.LatLng(data.latitude, data.longitude),
				title: "Avg. Velocity: " + data.speed + '\n\r' + "Device: " + data.device_id,
				icon: "http://hippo.ust.hk/img/link_dot.gif"
			});
		}
		else{
			marker = new google.maps.Marker({
				position: new google.maps.LatLng(approximated[0], approximated[1]),
				title: "Avg. Velocity: " + data.speed + '\n\r' + "Device: " + data.device_id,
				icon: "http://hippo.ust.hk/img/link_dot.gif"
			});
		}
		marker.upd = data;
        markers.push(marker);
        marker.setMap(map);
	}
	
	function approx_to_nearest_road(latt, longt)
	{
		var returnArr = new Array();
		dirServ.route({
			destination: new google.maps.LatLng(latt,longt), //43.780824,-114.506679
			origin: new google.maps.LatLng(latt,longt),
			travelMode: google.maps.TravelMode.DRIVING,
			unitSystem: google.maps.UnitSystem.METRIC,
		},function (dirRes, dirStat){
			if (dirStat == google.maps.DirectionsStatus.OK) {
				returnArr.push(dirRes.routes[0].legs[0].end_location.lat());
				returnArr.push(dirRes.routes[0].legs[0].end_location.lng());
				//alert(dirRes.routes[0].legs[0].end_location.lat());
			}
		});
		return returnArr;
	}
	
    function initialize(){
        var latlng = new google.maps.LatLng(30.102308, 31.239953);
		
        var myOptions = {
            zoom: 12,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
		
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        var marker;
		%{
			for (int i=0; i < updates.size(); i++){
				x = updates.get(i).longitude;
				y = updates.get(i).latitude;
				z = updates.get(i).speed;
				w = updates.get(i).client.device_id;
		}%
       
        marker = new google.maps.Marker({
            position: new google.maps.LatLng('${y}', '${x}'),
            title: "Avg. Velocity: ${z}"+'\n\r'+"Device: ${w}",
			icon: "http://hippo.ust.hk/img/link_dot.gif"
        });
		
        markers.push(marker);
        marker.setMap(map);
                
       	%{
			}
		}%
		
		
    }
	var timer_enable = 0;
	
	function clearTrafficOverlays()
	{
		if(polyLines.length)
			{
				for(ii = 0; ii < polyLines.length; ii++)
				{
					polyLines[ii].setMap(null);
				}
				polyLines.splice(0,polyLines.length);
				//alert(polyLines.length);
			}		
	}
	function do_poll()
	{
		if (timer_enable) {
			clearMarkers();
			clearTrafficOverlays();
			poll_updates();
			appyTrafficOverlays();
			setTimeout("do_poll()", 1000);
		}
	}
	
	function start_polling()
	{
		timer_enable = 1;
		do_poll();
	}
	
	function drawArea()
	{
		var ll;
		google.maps.event.addListener(map, 'rightclick', function(event){
			trigger_draw = 0;
			popz.close();
			if(rect)
				rect.setMap(null);
				clearTrafficOverlays();
			});
		google.maps.event.addListener(map, 'click', function(event){
			trigger_draw++;
			if (trigger_draw == 1) {
				popz.close();
				ll = event.latLng;
				if(rect)
					rect.setMap(null);
				clearTrafficOverlays();
			}
			else {
				rect = new google.maps.Rectangle({
					bounds: new google.maps.LatLngBounds(ll,event.latLng),
					fillColor: 'red'
				});
				rect.setMap(map);
				map.panTo(rect.getBounds().getCenter());
				map.setZoom(map.getZoom()+1);
				//popz.setContent('Whatever');
				popz.setPosition(rect.getBounds().getCenter());
				popz.open(map);
				//alert(rect.getBounds().getSouthWest());
				//alert(rect.getBounds().getNorthEast());
				//Do some more stuff
				trigger_draw = 0;
				if(!timer_enable)
				{
					var velocity = 0;
					var c = 0;
					var currDate = new Date().getTime();
					var timeDi = (currDate - lastUpd.date) / 60000;
					for(i=0; i<markers.length; i++)
					{
						if (markers[i].getPosition().lat() >= Math.min(rect.getBounds().getNorthEast().lat(), rect.getBounds().getSouthWest().lat())
						&& markers[i].getPosition().lat() <= Math.max(rect.getBounds().getNorthEast().lat(), rect.getBounds().getSouthWest().lat())
						&& markers[i].getPosition().lng() >= Math.min(rect.getBounds().getNorthEast().lng(), rect.getBounds().getSouthWest().lng())
						&& markers[i].getPosition().lng() <= Math.max(rect.getBounds().getNorthEast().lng(), rect.getBounds().getSouthWest().lng())
						) {
							velocity += markers[i].upd.speed;
							c++;
						}
					}
					$('#info').html('<div class="success"></div>');
					popz.setContent('Avg. Velocity: '+velocity/c+'<br>#Updates: '+c+'<br>Since '+timeDi+' mins.');
				}
			}
				
		});
	}
	
	function appyTrafficOverlays()
	{
		var j = 0;
		var veloc2,veloc1 = 0;
		for(i=0; i < markers.length; i++)
		{
			//myCluster.push(markers[i].getPosition());
			veloc1 = markers[i].upd.speed;
			while(j < markers.length)
			{
				var dirRequest = new Object();
				dirRequest.destination = markers[j].getPosition();
				dirRequest.origin = markers[i].getPosition();
				dirRequest.travelMode = google.maps.TravelMode.WALKING;
				dirRequest.unitSystem = google.maps.UnitSystem.METRIC;
				veloc2 = markers[j].upd.speed;
				dirServ.route(dirRequest,function (dirRes, dirStat){
						if (dirStat == google.maps.DirectionsStatus.OK) {
							if (dirRes.routes[0].legs[0].distance.value <= 100) {
								var myLine = new google.maps.Polyline({
											clickable: false				
											});
								var avg_v = (veloc1 + veloc2) / 2;
								var colr = (avg_v >= 60)? 'green' : (avg_v >= 40)? 'orange' : 'red';
								var optns = new Object();
								optns.path = dirRes.routes[0].overview_path;
								optns.strokeColor = colr;
								myLine.setOptions(optns);
								myLine.setMap(map);
								polyLines.push(myLine);
								//alert(polyLines.length);								
							}			
						}
					});
					j++;					
			}
			j = 0;		
			//Empty myCluster & reset veloc.
			//veloc = 0;
			//myCluster.splice(0,myCluster.length);
		}
	}
	
</script>
</head>
<body onload="initialize(); start_polling(); drawArea();">
	<div id="map_canvas" style="width:100%; height:60%">
    </div>
	<div id="bla" style="height:40%">
		<center>
		<div id="info">
			<div class="success"></div>
		#{if timeDiff}
		Showing data based on ${updates.size()} updates from the past ${timeDiff/60000} minutes.
		#{/if}
		#{else}
		Showing data based on ${updates.size()} updates from the past 1 Second.
		#{/else}
		</div>		
		<input type="button" id="resume" value="Resume RealTime" onclick="start_polling(); $('.success').hide(); $('#pause').attr('disabled',false); this.disabled=true; $('.success').html('Real Time Updates Resumed!').fadeIn('fast').fadeOut(5000);" disabled=true/>
		<input type="button" id="pause" value="Pause RealTime" onclick="timer_enable = 0; $('.success').hide(); $('#resume').attr('disabled',false); this.disabled=true; $('.success').html('Real Time Updates Paused!').fadeIn('fast').fadeOut(5000);" />
		</center>
	</div>
</body>
